<?php

/**
 * `Group controller dùng để xử lý các group
 */
class GroupController extends Controller {

	private function loadModel($id){
		$model= Group::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

    public function actionIndex(){
		$model= new Group('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Group']))
			$model->attributes = $_GET['Group'];

		$this->render('index', array(
			'model' => $model
		));
    }

    public function actionCreate(){
		$model = new Group();
		$this->ajaxValidate($model);
		if(Yii::app()->request->isPostRequest && !empty($_POST['Group'])){
			$model->setAttributes($_POST['Group'], false);
			if($model->validate()){
				$result = $model->updateGroup();
				if($result['success'] === true){
					Yii::app()->user->setFlash('success', $result['msg']);
					$this->redirect(Yii::app()->createUrl('groups'));
				}
			}
		}
		$this->render('create', array(
			'model' => $model
		));
    }


	public function actionUpdate($id){
		$model = $this->loadModel($id);
		$this->ajaxValidate($model);
		if(Yii::app()->request->isPostRequest && !empty($_POST['Group'])){
			$model->setAttributes($_POST['Group'], false);
			if($model->validate()){
				$result = $model->updateGroup();
				if($result['success'] === true){
					Yii::app()->user->setFlash('success', $result['msg']);
					$this->redirect(Yii::app()->createUrl('groups'));
				}
			}
		}
		$this->render('update', array(
			'model' => $model
		));
	}

	public function actionDelete($id){
		$group = $this->loadModel($id)->deleteGroup();
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
}